import 'dart:io';

import 'package:flutter/material.dart';
import 'package:isar/isar.dart';
import 'package:path_provider/path_provider.dart';

part 'main.g.dart';

@Collection()
class Contact {
  Id id = Isar.autoIncrement;
  late String name;
  late String phoneNumber;
  DateTime createdAt = DateTime.now();

  @override
  String toString() => 'Contact{id: $id, name: $name}';
}

Future<Isar> _repairIsarEnvironment(String path) async {
  try {
    print("_repairIsarEnvironment 1");
    // 1. 关闭所有可能的实例
    await Isar.getInstance()?.close();
    
    // 2. 删除损坏的环境文件
    final envDir = Directory('$path/default.isar');
    if (await envDir.exists()) {
      print("_repairIsarEnvironment 2");
      await envDir.delete(recursive: true);
    }
    
    // 3. 重建数据库
    print("_repairIsarEnvironment 3");
    var isar = await Isar.open(
      [ContactSchema],
      directory: path,
      inspector: true,
    );
    print("_repairIsarEnvironment 4");
    return isar;
  } catch (e) {
    print("_repairIsarEnvironment 5");
    // 终极回退：重置整个应用存储
    final appDir = Directory(path);
    await appDir.delete(recursive: true);
    rethrow;
  }
}

Future<Isar> initializeIsar() async {
  final dir = await getApplicationDocumentsDirectory();
  print("open dir: ${dir.path}");
  try {
    print("initializeIsar 1");
    var a = await Isar.open([ContactSchema], directory: dir.path, inspector: true,);
    print("initializeIsar 2");
    return a;
  } catch (e) {
    print("initializeIsar 3 $e");
    if (e.toString().contains('MDBX_PANIC')) {
      print("initializeIsar 4");
      return await _repairIsarEnvironment(dir.path);
    }
    print("initializeIsar 5");
    rethrow;
  }
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final isar = await initializeIsar();

  runApp(MyApp(isar: isar));
}

class MyApp extends StatelessWidget {
  final Isar isar;
  const MyApp({super.key, required this.isar});

    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        debugShowCheckedModeBanner: false,
        theme: ThemeData(primarySwatch: Colors.blue),
        home: ContactPage(isar: isar),
      );
    }
}

class ContactPage extends StatefulWidget {
  final Isar isar;
  const ContactPage({super.key, required this.isar});

  @override
  State<ContactPage> createState() => _ContactPageState();
}

class _ContactPageState extends State<ContactPage> {
    final _formKey = GlobalKey<FormState>();
    final _nameController = TextEditingController();
    final _phoneController = TextEditingController();

    Future<void> _addContact() async {

      final contact = Contact()
        ..name = _nameController.text
        ..phoneNumber = _phoneController.text;

        await widget.isar.writeTxn(() async {
          await widget.isar.contacts.put(contact);
        });

        _nameController.clear();
        _phoneController.clear();
        setState(() {});
    }

    Future<void> _deleteContact(int id) async {
      await widget.isar.writeTxn(() async {
        await widget.isar.contacts.delete(id);
      });
      setState(() {});
    }

    @override
    void dispose() {
      _nameController.dispose();
      _phoneController.dispose();
      super.dispose();
    }

    @override
    Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
              title: Text('Contact List'),
            ),
            body: Column(
                 children:[
                    Padding(
                        padding :const EdgeInsets.all(16.0),
                        child: Form(
                            key: _formKey,
                            child: Column(
                                children: [
                                    TextFormField(
                                        controller: _nameController,
                                        decoration: const InputDecoration(labelText: 'Name'),
                                        validator: (value) => value!.isEmpty ? 'Require' : null,
                                    ),
                                    TextFormField(
                                        controller: _phoneController,
                                        decoration: const InputDecoration(labelText: 'Phone Number'),
                                        validator: (value) => value!.isEmpty ? 'Require' : null,
                                    ),
                                    const SizedBox(height: 20),
                                    ElevatedButton(
                                        onPressed: _addContact,
                                        child: Text('Add Contact'),
                                    ),
                                ],
                            ),
                        )
                    ),
                    Expanded(
                        child: FutureBuilder<List<Contact>>(
                            future: widget.isar.contacts.where().findAll(),
                            builder: (context, snapshot) {
                                if(!snapshot.hasData) {
                                    return Center(child: CircularProgressIndicator());
                                }
                                final contacts = snapshot.data!;
                                return ListView.builder(
                                    itemCount: contacts.length,
                                    itemBuilder: (context, index) {
                                        final contact = contacts[index];
                                        return ListTile(
                                            title: Text(contact.name),
                                            subtitle: Text(contact.phoneNumber),
                                            trailing: IconButton(
                                                icon: const Icon(Icons.delete,color: Colors.red),
                                                onPressed: () => _deleteContact(contact.id),
                                            ),
                                        );
                                    },
                                );
                            },
                        ),
                    ),
                 ]
            )
        );
    }
}